import Ajax from './ajax'
import Cos from 'cos-js-sdk-v5'

var tempCert

const getCert = function (callback) {
  Ajax.get('common/oss/cert')
    .then(res => {
      if (res.code == 0) {
        tempCert = res.data
        if (callback) callback()
      }
    })
    .catch(err => {
      console.error(err)
    })
}

const getCos = function (callback, ...params) {
  var now = new Date().getTime() / 1000
  if (!tempCert || !tempCert.secretId || now >= tempCert.expire) {
    getCert(function () {
      var cos = new Cos({
        SecretId: tempCert.secretId,
        SecretKey: tempCert.secretKey,
        SecurityToken: tempCert.token
      })
      if (callback) callback(cos, params)
    })
  } else {
    var cos = new Cos({
      SecretId: tempCert.secretId,
      SecretKey: tempCert.secretKey,
      SecurityToken: tempCert.token
    })
    if (callback) callback(cos, params)
  }
}

const removeObj = function (remoteName, callback) {
  getCos(
    function (cos, params) {
      var key = params[0]
      var callback = params[1]
      cos.deleteObject(
        {
          Bucket: tempCert.bucket,
          Region: tempCert.region,
          Key: key
        },
        function (err, data) {
          if (callback) callback(err, data)
        }
      )
    },
    remoteName,
    callback
  )
}

const upload = function (file, remoteName, callback) {
  getCos(
    function (cos, params) {
      var file = params[0]
      var key = params[1]
      var callback = params[2]

      cos.uploadFile(
        {
          Bucket: tempCert.bucket,
          Region: tempCert.region,
          Key: key,
          Body: file,
          SliceSize: 1024 * 1024 * 5, //分块上传文件
          onProgress(data) {
            //上传进度
          },
          onFileFinish(err, data, opt) {
            if (callback) callback(err, data)
          }
        },
        function (err, data) {}
      )
    },
    file,
    remoteName,
    callback
  )
}
// 文件上传到腾讯云和从云平台移除
export default {
  upload: upload,
  remove: removeObj
}
